package com.qiwx.pigeon.base;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.view.Gravity;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.facebook.common.internal.Throwables;
import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.DBSqlUtil;
import com.qiwx.pigeon.Utils.DateTimeUtils;
import com.qiwx.pigeon.Utils.LogUtil;
import com.qiwx.pigeon.Utils.MyToast;
import com.qiwx.pigeon.activity.common.SelectDateActivity;
import com.qiwx.pigeon.app.AppManager;
import com.qiwx.pigeon.data.vo.WareHouseBean;
import com.qiwx.pigeon.eventbus.DbUpdateEvent;
import com.qiwx.pigeon.helper.LoadingDialog;
import com.qiwx.pigeon.widget.SelectDatePopWindow;
import com.trello.rxlifecycle.LifecycleProvider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.subscriptions.CompositeSubscription;

import static com.qiwx.pigeon.activity.common.SelectDateActivity.REQUEST_CODE_END;
import static com.qiwx.pigeon.activity.common.SelectDateActivity.REQUEST_CODE_START;

/**
 * @description
 * @Author qiwx
 * @Date 2020-03-23 11:36
 **/
public abstract class BaseActivity extends AppCompatActivity implements IBasePolicy, IBaseView {
    protected String TAG = getClass().getSimpleName();
    protected CompositeSubscription mSubscription;
    Unbinder mUnbinder;
    private static List<WareHouseBean> data = new ArrayList<>();
    private int mShowNetCount = 0;
    protected SelectDatePopWindow popWindow;
    public static final int REQUEST_CODE_ASK_CALL_PHONE = 10001;//电话权限


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        setContentView(getLayoutId());
        mUnbinder = ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        initAfterOnCreate();

    }

    public void onPause() {
        super.onPause();
        if (mSubscription != null) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
    }

    protected CompositeSubscription getSubscription() {
        if (null == mSubscription) {
            mSubscription = new CompositeSubscription();
        }
        return mSubscription;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onGetStickyEvent(DbUpdateEvent updateEvent) {
        LogUtil.e("TAG", "数据库更新");
        dbUpdate();

    }

    private void mustRunOnMainThread() {
        if (Looper.getMainLooper() != Looper.myLooper()) {
            Throwables.propagate(new IllegalThreadStateException("方法必须在主线程调用"));
        }
    }

    public void showError(String error) {
        dismissLoading();
        MyToast.showLong(error);
    }

    public void showLoading() {
        mustRunOnMainThread();
        mShowNetCount++;
        LogUtil.e(TAG, "show mShowNetCount:" + mShowNetCount);
        LoadingDialog.showLoading(this);
    }

    public void showLoading(String msg) {
        mustRunOnMainThread();
        mShowNetCount++;
        LogUtil.e(TAG, "show 1 mShowNetCount:" + mShowNetCount);
        LoadingDialog.showLoading(this, msg, true);
    }

    public void showLoading(String msg, boolean isCanCancel) {
        mustRunOnMainThread();
        mShowNetCount++;
        LogUtil.e(TAG, "show 2 mShowNetCount:" + mShowNetCount);
        LoadingDialog.showLoading(this, msg, isCanCancel);
    }

    public void dismissLoading() {
        mustRunOnMainThread();
        mShowNetCount--;
        if (mShowNetCount <= 0) {
            mShowNetCount = 0;
            LoadingDialog.disDialog();
        }
        LogUtil.e(TAG, "dismiss mShowNetCount:" + mShowNetCount);
    }

    public void onSingleLoginView(String msg) {

    }//单点登录  被踢 接口

    public void onNoLogin(String msg) {

    }//未登录

    public void onUserDisable(String msg) {

    }//禁止用户


    public void dbUpdate() {

    }

    public void selectStartDate() {
        selectDate("2019-01", 0);
    }

    //选择日期
    public void selectDate(String date, int type) {
        date = date.replace("年", "")
                .replace("日", "");
        String[] arr = date.split("-");
        if (popWindow == null) {
            popWindow = new SelectDatePopWindow(this);
            popWindow.setListener((t, content) -> {

                onSelectDate(t, content);

            });
        }
        if (type == 0) {
            popWindow.setTitle("开始日期");
        } else {
            popWindow.setTitle("结束日期");
        }
        popWindow.initData(type, Integer.valueOf(arr[0]), Integer.valueOf(arr[1]));

        //这种方式无论有虚拟按键还是没有都可完全显示，因为它显示的在整个父布局中
        popWindow.showAtLocation(findViewById(R.id.lin_main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    protected void onSelectDate(int type, String content) {

    }

    //选择有效期
    public void selectStartValiDate(String title) {
        Intent intent = new Intent(this, SelectDateActivity.class);
//        intent.putExtra("term", 3);
        intent.putExtra("MinMonth", DateTimeUtils.getMonth4String("1990-01"));
        intent.putExtra("Minyear", DateTimeUtils.getYear4String("1990-01"));
        intent.putExtra(Constant.KEY_TITLE, title);
        startActivityForResult(intent, REQUEST_CODE_START);
    }

    public void selectEndValiDate(String startDate) {
        if (startDate == null || startDate.equals("")) {
            MyToast.showShort("先选择开始日期");
            return;
        }
        startDate = startDate.replace("年", "")
                .replace("日", "");

        String[] arr = startDate.split("-");
        Intent intent = new Intent(this, SelectDateActivity.class);
//        intent.putExtra("term", 3);
        intent.putExtra("Minyear", arr[0]);
        intent.putExtra("MinMonth", arr[1]);
        intent.putExtra(Constant.KEY_TITLE, "结束日期");
        startActivityForResult(intent, REQUEST_CODE_END);
    }

    public void forceDismissLoading() {
        if (mShowNetCount > 0) {
            setShowNetCount(0);
            dismissLoading();
        }
    }

    private void setShowNetCount(int mShowNetCount) {
        this.mShowNetCount = mShowNetCount;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnbinder != null) {
            mUnbinder.unbind();
            mUnbinder = null;
        }
        EventBus.getDefault().unregister(this);
    }

    public void requestPermission(String phone) {

    }

    /**
     * 注册权限申请回调
     *
     * @param requestCode  申请码
     * @param permissions  申请的权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_CALL_PHONE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    MyToast.showCenterShort("申请电话权成功！");
                } else {
                    // Permission Denied
                    MyToast.showCenterShort("申请电话权限被拒绝！");
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * 拨打电话（直接拨打）
     *
     * @param
     */
    public void callPhone(String phone) {

        //判断Android版本是否大于23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);

            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE},
                        REQUEST_CODE_ASK_CALL_PHONE);
                return;
            } else {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
                startActivity(intent);
            }
        } else {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
            startActivity(intent);
        }

    }

}
